package com.hcy.app.screen.relax

import android.app.Activity
import android.content.Context
import android.content.pm.ActivityInfo
import android.net.Uri
import android.util.Log
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.LinearLayout.HORIZONTAL
import android.widget.TextView
import androidx.activity.ComponentActivity
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Place
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import java.io.File
import androidx.core.net.toUri


@Composable
fun Video_Page(
    viewModel: RelaxViewModel = hiltViewModel(LocalContext.current as ComponentActivity)
) {
    val ctx = LocalContext.current
    val relaxState by viewModel.relaxState.collectAsState()
    var isLandscape by remember { mutableStateOf(true) }
    var showToolbar by remember { mutableStateOf(true) }
    val currentFile = File(relaxState.currentFile?.filePath.toString())
    val videoUri = remember {
        "file:///${relaxState.currentFile?.filePath.toString()}".toUri()
    }
    val modifier = remember{
        if (isLandscape) {
            // 竖屏：100%宽，50%高
            Modifier
                .fillMaxWidth()
                .fillMaxHeight(0.5f)
        } else {
            // 横屏：100%宽高
            Modifier.fillMaxSize()
                .clickable{
                    Log.d("miao","showToolbar:${showToolbar}")
                    showToolbar = !showToolbar
                }
        }
    }


    Column(
        modifier = Modifier.fillMaxSize()
            .clickable{
                Log.d("miao","showToolbar:${showToolbar}")
                showToolbar = !showToolbar
            }
    ) {
        // 播放器
        VideoPlayer(
            videoUri = videoUri,
            modifier = modifier
        )
        // 自定义控制区
        val exoPlayer = rememberExoPlayer(videoUri = videoUri)
        var isPlaying by remember { mutableStateOf(false) }

        if (isLandscape){
            Row(verticalAlignment = Alignment.CenterVertically) {
                IconButton(onClick = {
                    isPlaying = !isPlaying
                    exoPlayer.playWhenReady = isPlaying
                }) {
                    Icon(
                        imageVector = if (isPlaying) Icons.Default.Place else Icons.Default.PlayArrow,
                        contentDescription = null
                    )
                }
                Text(
                    text = "${exoPlayer.currentPosition.toSeconds()}/${exoPlayer.duration.toSeconds()}",
                    modifier = Modifier.padding(horizontal = 8.dp)
                )
                Button(
                    onClick = {
                        isLandscape = !isLandscape
                        // 切换屏幕方向
                        (ctx as Activity).requestedOrientation =
                            if (isLandscape) {
                                ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE // 竖屏（垂直方向）
                            } else {
                                ActivityInfo.SCREEN_ORIENTATION_PORTRAIT // 横屏（水平方向）
                            }
                    }
                ) {
                    Text(if (isLandscape) "切换为竖屏" else "切换为横屏")
                }
            }
        }

    }
}

fun Long.toSeconds(): String = (this / 1000).toString()

@Composable
fun VideoPlayer(
    videoUri: Uri,
    modifier: Modifier = Modifier
) {
    val context = LocalContext.current
    val exoPlayer = rememberExoPlayer(videoUri = videoUri)
    var showCustomUI by remember { mutableStateOf(false) }

    DisposableEffect(Unit) {
        onDispose { exoPlayer.release() }
    }

    AndroidView(
        factory = { ctx ->
            PlayerView(ctx).apply {
                player = exoPlayer
                useController = true // 启用默认控制栏

                // 添加自定义覆盖层
                addView(LinearLayout(ctx).apply {
                    orientation = HORIZONTAL
                    layoutParams = FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)

                    addView(TextView(ctx).apply {
                        text = "自定义文本2"
//                        visibility = if (showCustomUI) VISIBLE else GONE
                    })


                    addView(TextView(ctx).apply {
                        text = "自定义文本1"
                        visibility = if (showCustomUI) VISIBLE else GONE
                        modifier.clickable{
                            Log.d("miao","自定义文本1被点击")
                        }
                    })
                })

            }
        },
        modifier = modifier
            .pointerInput(Unit){
                detectTapGestures(
                    onDoubleTap = { offset ->
                        Log.d("miao","offset:${offset}")
//                        if (offset.x > size.width / 2) {
//                            exoPlayer.seekForward()
//                        } else {
//                            exoPlayer.seekBack()
//                        }
                    }
                )


            }
    )
}




@Composable
fun rememberExoPlayer(
    context: Context = LocalContext.current,
    videoUri: Uri
): ExoPlayer {
    return remember {
        ExoPlayer.Builder(context).build().apply {
            val mediaItem = MediaItem.fromUri(videoUri)
            setMediaItem(mediaItem)
            prepare()
        }
    }.also { player ->
        DisposableEffect(player) {
            onDispose {
                player.release() // 释放资源
            }
        }
    }
}